package com.app.lol.jungleTime;

import java.awt.Color;

/**
 * This class implements Runnable because a class which implement Thread cant be reloaded 
 */
public class MonsterChrono implements Runnable {
	
	//------------------------
	//		Attributes
	//------------------------
	
	private Thread currentThread = null;
	
	private String chronoName;
	private Color color;
	
	private int sec;
	private int initialValue;
	private int midValue;
	
	/** Temporary value, when thread is running */
	private TextChronoField tmpTextChronoField;
	
	//------------------------
	//		Constructor
	//------------------------
	
	public MonsterChrono(String chronoName, Color color, int initialValue) {
		this.chronoName = chronoName;
		this.color = color;
		this.sec = initialValue;
		this.initialValue = initialValue;
		this.midValue = ((int) Math.floor(initialValue/2)) + 1;
	}
	
	//------------------------
	//	 	  Method
	//------------------------
	
	/** Throw a new thread */
	public void startChrono(TextChronoField textChronoField) {
		tmpTextChronoField = textChronoField;
		
		if(currentThread != null && currentThread.isAlive()) return;
		
		currentThread = new Thread(this);
		currentThread.start();
	}
	
	//------------------------
	//	 	 Thread
	//------------------------
	
	/** 
	 * Called by start()
	 * Decrease the chrono
	 */
	public void run() {
		
		sec = initialValue;
		tmpTextChronoField.setText(""+sec);
		tmpTextChronoField.setBackground(TextChronoField.STARTCOLOR);
		
		boolean midValueDone = false;
		
		while(sec > 1)
		{	
			sec--;
			tmpTextChronoField.setText(""+sec);
			
			if(!midValueDone && sec < midValue)
			{
				tmpTextChronoField.setBackground(TextChronoField.MIDCOLOR);
				midValueDone = true;
			}
			
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		tmpTextChronoField.setText("GO !");
		tmpTextChronoField.setBackground(TextChronoField.ENDCOLOR);
		
	}
	
	/** To stop the thread in security */
	public synchronized void stopThread() {
		currentThread.interrupt();
	} 

	//------------------------
	//	 Setter/Getter/Is
	//------------------------
	
	public String getChronoName() {
		return chronoName;
	}
	
	public Color getColor() {
		return color;
	}

	public int getInitialValue() {
		return initialValue;
	}
	
	public void setTmpTextChronoField(TextChronoField tmpTextChronoField) {
		this.tmpTextChronoField = tmpTextChronoField;
	}
	
}
